import {
  useEffect,
  useState,
  useCallback,
  useImperativeHandle,
  useRef,
} from 'react';
import { Input, Spin, Table, Checkbox, Empty, Tree } from 'antd';
import { CloseCircleFilled } from '@ant-design/icons';
import { Key } from 'antd/es/table/interface';
import { TextWidget, getMessage } from '@inbiz/react';
import Pagination from '@inbiz/basic/Pagination'
import { InbizIcon, pageGroupOneToTwo } from '@inbiz/utils';
import { getGroupList, getGroupPageList } from '../services';
import styles from '../index.less';

const PagePicker = (props: any) => {
  const { appInfo, showTagList } = props;
  // 当前选中分组
  const [activeGroup, $activeGroup] = useState('');
  // 组列表数据
  const [groupList, $groupList] = useState<any[]>([]);
  // 选择数据Outid
  const [selecteds, $selecteds] = useState<any[]>([]);
  // 选择数据详情
  const [selectedsInfo, $selectedsInfo] = useState<any[]>([]);
  // 页面列表数据
  const [dataSource, $dataSource] = useState<any[]>([]);
  // 组列表加载
  const [groupLoading, $groupLoading] = useState<boolean>(false);
  // 页面列表加载
  const [pageLoading, $pageLoading] = useState<boolean>(false);
  // 当前页码
  const [current, $current] = useState<number>(1);
  // 当前分页数值
  const [pageSize, $pageSize] = useState<number>(10);
  // 页面总数
  const [pageTotal, $pageTotal] = useState<number>(0);
  // 分组数据获取状态（是否成功）
  const [loadGroup, $loadGroup] = useState<boolean>(false);
  // 搜索框文本
  const [searchIpts, $searchIpts] = useState<string>('');
  // 实际搜索框文本
  const [searchValue, $searchValue] = useState<string>('');
  // 是否全局搜索
  const [searchAll, $searchAll] = useState<boolean>(true);
  // 搜索框Dom
  const searchRef: any = useRef();
  // 站点名称
  const appName = appInfo.Name;

  // 向父组件暴露提交方法
  useImperativeHandle(
    props.refs,
    () => ({
      submit: submit,
    }),
    [selectedsInfo],
  );

  // 初始化获取分组列表
  useEffect(() => {
    $groupLoading(true);
    getGroupList(appInfo)
      .then(async (res) => {
        if (Array.isArray(res)) {
          let list: any[] = await pageGroupOneToTwo(res);
          $groupList(list);
          $loadGroup(true);
        }
        $groupLoading(false);
      })
      .catch(() => {
        $groupLoading(false);
      });
  }, []);

  // 组变化获取页面列表数据
  useEffect(() => {
    $current(1);
    $pageLoading(true);
    const page = {
      skipCount: 0,
      maxResultCount: pageSize,
    };
    getGroupPageList(appInfo, activeGroup, page)
      .then((res) => {
        $dataSource(res.Data);
        $pageTotal(res.Total);
        $pageLoading(false);
      })
      .catch(() => $pageLoading(false));
  }, [activeGroup]);

  // 搜索页面
  const searchPage = useCallback(
    (searchTxt: string) => {
      if (!loadGroup) {
        return;
      }
      const page = {
        skipCount: 0,
        maxResultCount: pageSize,
        SearchText: searchTxt?.trim(),
        isSearchAll: searchTxt?.trim() !== '' && searchAll,
      };
      $pageLoading(true);
      getGroupPageList(appInfo, activeGroup, page)
        .then((res) => {
          $dataSource(res.Data);
          $pageTotal(res.Total);
          $pageLoading(false);
        })
        .catch(() => $pageLoading(false));
    },
    [loadGroup, activeGroup, pageSize, searchAll],
  );

  // 选中组
  const clickGroup = (id: any) => {
    $activeGroup(id);
    $searchIpts('');
    $searchValue('');
  };

  // 分页器更新值
  const paginationChange = useCallback(
    (e: any) => {
      $current(e.current);
      $pageSize(e.pageSize);
      $pageLoading(true);
      const page = {
        skipCount: (e.current - 1) * e.pageSize,
        maxResultCount: e.pageSize,
        SearchText: searchValue?.trim(),
        isSearchAll: searchValue?.trim() !== '' && searchAll,
      };
      getGroupPageList(appInfo, activeGroup, page)
        .then((res) => {
          $dataSource(res.Data);
          $pageTotal(res.Total);
          $pageLoading(false);
        })
        .catch(() => $pageLoading(false));
    },
    [searchValue, activeGroup, searchAll],
  );

  // 筛选搜索值更新
  const searchChange = (e: any) => {
    $searchIpts(e.target.value);
  };

  // 多选变化
  const checkGroupChange = useCallback(
    (e) => {
      let arr = [...selecteds];
      let arrInfo = [...selectedsInfo];
      dataSource.map((item) => {
        arr = arr.filter((val) => val !== item.OutId);
        arrInfo = arrInfo.filter((val) => val.OutId !== item.OutId);
      });
      e.map((item: any) => {
        let info = dataSource.filter((val) => val.OutId === item);
        arrInfo.push(...info);
      });
      arr = [...arr, ...e];
      $selecteds(arr);
      $selectedsInfo(arrInfo);
      props.totalChange && props.totalChange(arr.length);
    },
    [selecteds, dataSource, selectedsInfo],
  );

  // 多选点击行选择/取消
  const rowClick = useCallback(
    (record: any) => {
      if (Array.isArray(selecteds)) {
        let select = [...selecteds];
        let arrInfo = [...selectedsInfo];
        if (select?.indexOf(record.OutId) > -1) {
          let idx = select?.indexOf(record.OutId);
          if (idx || idx === 0) select?.splice(idx, 1);
          let idx1 = arrInfo?.findIndex((item) => item.OutId === record.OutId);
          if (idx1 || idx === 0) arrInfo?.splice(idx1, 1);
        } else {
          select.push(record.OutId);
          arrInfo.push({ ...record });
        }
        $selecteds(select);
        $selectedsInfo(arrInfo);
        props.totalChange && props.totalChange(select.length);
      }
    },
    [selecteds, selectedsInfo],
  );

  // 确定选中页面数据
  const submit = useCallback(() => {
    if (Array.isArray(selectedsInfo)) {
      return selectedsInfo;
    }
    return [];
  }, [selectedsInfo]);

  // 表格结构
  const columns = [
    {
      title: getMessage('PermissionConfig.page_nane'),
      dataIndex: 'Name',
      key: 'Name',
      width: 530,
      render: (txt: string) => <TextWidget>{txt}</TextWidget>,
    },
  ];

  return (
    <div className={styles['inbiz-component-permission-config-page-picker']}>
      <Spin spinning={props.checkLoading}>
        <div className={styles['content']}>
          <div className={styles['left-tree']}>
            <p
              onClick={() => {
                $activeGroup('');
                $searchValue('');
                $searchIpts('');
              }}
              className={styles[activeGroup === '' ? 'app-selected' : '']}
            >
              <InbizIcon
                type="icon-yingyongmingcheng"
                style={{
                  fontSize: '16px',
                  color: 'var(--inbiz-color-primary)',
                }}
              />
              <span className={styles['app-name']} title={getMessage(appName)}>
                <TextWidget>{appName}</TextWidget>
              </span>
            </p>
            <Spin spinning={groupLoading}>
              <div
                className={styles['left-group-box']}
                style={{ maxHeight: showTagList ? 336 : 436 }}
              >
                <Tree
                  showIcon
                  fieldNames={{
                    key: 'OutId',
                    children: 'Children',
                  }}
                  onSelect={(keys: Key[]) => clickGroup(keys?.[0] || '')}
                  selectedKeys={activeGroup !== '' ? [activeGroup] : []}
                  treeData={groupList}
                />
              </div>
            </Spin>
          </div>
          <div className={styles['right-nav']}>
            <Spin spinning={pageLoading}>
              <div className={styles['right-title']}>
                <Input
                  ref={searchRef}
                  value={searchIpts}
                  onChange={searchChange}
                  onPressEnter={(e: any) => {
                    $current(1);
                    $searchValue(e.target.value);
                    searchPage(e.target.value);
                  }}
                  placeholder={getMessage('PermissionConfig.search_placeholder')} // 请输入页面名称
                  suffix={
                    <InbizIcon
                      type="icon-ic-sousuo"
                      style={{ color: '#999' }}
                      onClick={() => {
                        $current(1);
                        $searchValue(searchRef.current?.input?.value || '');
                        searchPage(searchRef.current?.input?.value || '');
                      }}
                    />
                  }
                />
                <Checkbox
                  checked={searchAll}
                  onChange={(e) => $searchAll(e.target.checked)}
                >
                  <TextWidget>PermissionConfig.check_all</TextWidget>{' '}
                  {/* 包含应用内全部页面 */}
                </Checkbox>
              </div>
              <div className={styles['page-list']}>
                <Table
                  columns={columns}
                  dataSource={dataSource}
                  // loading={pageLoading}
                  size="small"
                  rowKey="OutId"
                  pagination={false}
                  scroll={{ y: showTagList ? 250 : 350 }}
                  rowSelection={{
                    selectedRowKeys: selecteds,
                    onChange: checkGroupChange,
                  }}
                  onRow={(record: { OutId: string }) => {
                    return {
                      onClick: (e) => {
                        e.stopPropagation();
                        rowClick(record);
                      },
                    };
                  }}
                  locale={{
                    emptyText: (
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={
                          <TextWidget>PermissionConfig.no_data</TextWidget>
                        }
                      />
                    ),
                  }}
                />
              </div>
              <Pagination
                size="small"
                options={[10, 20, 30, 40, 50]}
                total={pageTotal}
                current={current}
                pageSize={pageSize}
                onChange={paginationChange}
              />
            </Spin>
          </div>
        </div>
      </Spin>
      {showTagList && (
        <div className={styles['checked-list']}>
          {selectedsInfo.map((item: any) => {
            return (
              <div className={styles['checked-item']}>
                <span>
                  <TextWidget>{item.Name}</TextWidget>
                </span>
                <CloseCircleFilled onClick={() => rowClick(item)} />
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default PagePicker;
